// ==UserScript==
// @name         miWork
// @namespace    liqing
// @version      0.3
// @description  小米工作台脚本
// @author       liqing
// @include      https://cs.pt.xiaomi.com/web/*
// @grant        GM_xmlhttpRequest
// @grant        GM_addStyle
// @connect      *
// @updateURL    https://gitee.com/liqing_study/Tampermokey/blob/master/miWork1.js
// ==/UserScript==

//根据页面id值避免脚本相互影响冲突
var i_dashboard = document.querySelector("#dashboard");
var table_case, caseItems,table_case_parent;
//小米id集合
var miIdDatas = [],caseTdList=[];
//插入按钮位置，一键外呼提交按钮，取消按钮,添加轮次按钮
var resert, pageSubmitBtn, pageCloseBtn, addCallBtn;
//一键外呼发送的数据
var callDatas = {};
//坐席名字，一键外呼表数据,外呼轮次,轮次集合
var username, strategy = {},
    rounds = [];
var callList;
var callStats = {},callStatsJson;

//外呼进度查询返回数据
var callStatusDatas = {};
var bsc_port = "10.180.200.50:9016/api/xiaomi";
var comm_port = "10.180.200.50:9019/api/xiaomi";
//轮询变量
var autoRound;
//暂停恢复按钮,外呼进度的状态值
var pauseStatusBtn,callOutStatus=0;
//机构id
var orgId = 91;

setTimeout(() => {
    i_dashboard = document.querySelector("#dashboard");
    if (i_dashboard) {
        console.log("小米催收管理工作台");
        addAlert();
        table_case_parent = document.querySelector(".table-striped");
        var c_username = document.querySelector(".username");
        username = c_username.innerText;

        if (!c_username) {
            c_username = document.querySelector(".username");
        }
        username = c_username.innerText;
        callDatas.orgId = orgId;
        callDatas.customerId = getCookie("userId") + "#";
        //讲cookie存储到本地
        localStorage.setItem("hjzdUserId", callDatas.customerId);
        callDatas.customerName = username;
        insertPage();
        insertCallPage();
        callList = document.querySelector("#callList");
        getSubmitBtn("一键提交",autoCaseClick);
        getSubmitBtn("外呼进度", callStatusBtn);
        getSubmitBtn("一键外呼", openCallPageBtn);

        //轮询        
        callStats.orgId = orgId;
        callStats.customerId = getCookie("userId") + "#";
        callStatsJson = JSON.stringify(callStats);
        
        
        setInterval(function() {
            GM_xmlhttpRequest({
                method: "POST",
                url: "http://" + comm_port + "/comm/callStatus",
                headers: {
                    "Content-Type": "application/json"
                },
                data: callStatsJson,
                onload: function(res) {
                    if (res.status == 200) {
                        var callData = JSON.parse(res.responseText + "");
                        if (callData.statusCode != 200) {
                            return;
                        }
                        var data = callData.data;
                        if (data) {
                            var infos = data.split("#");
                            var successCallInfo = infos[infos.length - 1];
                            successCallInfo.substr(0, successCallInfo.length - 1);
                            //存储打电话成功的卡人信息
                            localStorage.setItem("callInfo", successCallInfo);
                            //新标签页打开案件信息显示消息
                            window.open("https://cs.pt.xiaomi.com/web/#/ticket/case/detail/" + infos[0] + "/" + infos[1] + "/%7B%7D");
                        }
                    }
                },
                onerror: function(err) {
                    console.log(err);
                }
            });
            //催记状态轮询
            GM_xmlhttpRequest({
              method: "POST",
              url: "http://" + comm_port + "/comm/record",
              headers: {
                  "Content-Type": "application/json"
              },
              data: callStatsJson,
              onload: function(res) {
                if (res.status == 200) {
                  let responseText = JSON.parse(res.responseText + "");
                  let recordData = responseText.data;
                  if(recordData){
                    console.log(recordData);
                    let recordStr = recordData.split("#");
                    if(recordStr.length >= 4 && recordStr[2]) {
                      let miIdfi = recordStr[2];
                      let content;
                      if(recordStr[3] == 0)
                        content = "无人接听"; 
                      else
                        content = "AI语音播报";
                      let requestData =  {caseId:recordStr[0],collectionContactType:"1",complaintTendency:"1",consentAmount:null,consentTime:null,contactDetailResult:"311",
                        content:content,mifiId:recordStr[1],mobile:miIdfi,phoneType:"1",repaymentType:null,title:1,valid:"0"};  
                      let requestJson = JSON.stringify(requestData);
                      console.log("开始请求写催记");
                      console.log(requestJson);
                      setRecord(requestJson,recordStr[0],recordStr[1]);                 
                    }else{
                      console.log("加密手机号返回为空");
                    }
                  }
                }
              },
              onerror: function(err) {
                console.log(err);
              }
            });             
        }, 3000);

        

    } else {
        console.log("没有监听到页面元素");
    }
}, 2000);

function getCookie(cookieName) {
  //将document.cookie保存在变量cookie中
  var cookie = document.cookie;
  //在cookie中查找cookieName的位置保存在i中
  var i = cookie.indexOf(cookieName);
  //如果i等于-1,就返回null
  if (i == -1) {
      return null
  } else { //否则  
      //i+cookieName的长度+1,保存在变量starti中
      var starti = i + cookieName.length + 1;
      //从starti开始查找cookie中下一个;的位置endi
      var endi = cookie.indexOf(";", starti);
      if (endi == -1) { //如果endi是-1
          //截取cookie中starti到结尾的剩余内容,返回
          return cookie.slice(starti);
      } else { //否则
          //截取cookie中starti到endi的内容，返回
          return cookie.slice(starti, endi);
      }
  }
}

//请求写催记接口
function setRecord(requestData,caseId,customerCode){
  console.log("请求写催记");
  let cookie = document.cookie;
  GM_xmlhttpRequest({
    method: "post",
    url: "https://cs.pt.xiaomi.com/cs/contact/remark",
    headers: {
      "Accept": "application/json, text/plain, */*",
      "Accept-Encoding": "gzip, deflate, br",
      "Accept-Language": "zh-CN,zh;q=0.9",
      "Connection": "keep-alive",
      "Content-Type": "application/json;charset=UTF-8",
      "Cookie": cookie,
      "Host": "cs.pt.xiaomi.com",
      "Location-Hash": `#/ticket/case/detail/${caseId}/${customerCode}/%7B%7D`,
      "Origin": "https://cs.pt.xiaomi.com",
      "Referer": "https://cs.pt.xiaomi.com/web/",
      "Sec-Fetch-Mode": "cors",
      "Sec-Fetch-Site": "same-origin",
      "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36"
    },
    data:requestData,
    onload: function(res) {
      console.log(res);
      if (res.status == 200) {
        console.log("协催及成功");
        showAlert("写催记成功");
      }
    },
    onerror: function(err) {
      showAlert("请求错误，请稍后再试");
      console.log(err);
    }
  })
}

//外呼按钮插入
function getSubmitBtn(btnName, btnFunc) {
  if (table_case_parent == null) {
      var table_case_parent = document.querySelector(".table-striped");
      var c_pullRight = document.querySelectorAll(".pull-right");
  }
  
  let item = c_pullRight.length-1;
  resert = c_pullRight[item];
  var newEle = document.createElement("button");
  var textnode = document.createTextNode(btnName);
  newEle.appendChild(textnode);
  newEle.style.minWidth = 80 + 'px';
  newEle.style.height = 30 + "px";
  newEle.style.background = "#378AFE";
  newEle.style.border = "1px solid #0678F4"
  newEle.style.color = "#fff";
  newEle.style.marginRight = "10px"
  newEle.style.padding = "0 10px";

  var submitBtn = resert.parentNode.insertBefore(newEle, resert.nextSibling);
  submitBtn.addEventListener("click", btnFunc);
  
}

//获取表中的小米id
function getCaseTable() {
  if (!table_case_parent) {
      table_case_parent = document.querySelector(".table-striped");
  }
  if (table_case_parent) {
      table_case = table_case_parent.querySelector("tbody");
      caseItems = table_case.querySelectorAll("tr");
      miIdDatas=[],caseTdList=[];
      for (let index = 0; index < caseItems.length; index++) {
          var c_ngScopes = caseItems[index].querySelectorAll(".ng-scope");
          var inputType = caseItems[index].querySelector("input");
          if (inputType && inputType.checked) {
              var miId = c_ngScopes[2].innerText;
              miIdDatas.push(miId);
              let caseTd = c_ngScopes[1];
              caseTdList.push(caseTd);  
          }
      }
  }
}
var isAutoCase = true;
var isUproadData = false;
//自动点击案件编号
function autoCaseClick(){
  getCaseTable();
  if (miIdDatas.length === 0) {
    showAlert("请勾选数据再外呼");
    return;
  }
  if(isAutoCase) {
    let uploadList = {orgId:orgId,customerId:getCookie("userId") + "#",data:miIdDatas};
    let uploadListJson = JSON.stringify(uploadList);
    isAutoCase = false;
    //未提交的案件编号数据
    let requestCaseData=[];
    GM_xmlhttpRequest({
      method: "POST",
      url: "http://" + bsc_port + "/call/upload-list-status",
      headers: {
          "Content-Type": "application/json"
      },
      data: uploadListJson,
      onload: function(res) {
          if (res.status == 200) {
            let responseData = JSON.parse(res.responseText + "");
            let miData = responseData.data;
            for (let i = 0; i < miIdDatas.length; i++) {
              for (let j = 0; j < miData.length; j++) {
                if(miIdDatas[i] === miData[j]){
                  requestCaseData.push(caseTdList[i]);
                  break;
                }
              }
            }
            let index=0;
            if(miData.length){
              showAlert("开始一键提交数据");
              isUproadData = true;
              let autoInterval = setInterval(function(){
                localStorage.setItem("autoClick","true");
                requestCaseData[index].click();
                index++;
                if(index >= requestCaseData.length){
                  isUproadData = false;
                  isAutoCase = true;
                  clearInterval(autoInterval);
                  showAlert("一键提交完成");
                }
              }, 6000);
            }else{
              isAutoCase = true;
              showAlert("选中的数据已提交");
            }
          }
      },
      onerror: function(err) {
        console.log(err);
      }
    });
  }
}


//一键外呼打开弹框
function clickCall() {
  var page = document.querySelector("#page");
  if (!page) {
      console.log("没有获取到插入页面");
  }
  page.style.display = "block";
  var closePageBtn = document.querySelector("#closePage");
  closePageBtn.addEventListener("click", closeCallPageBtn);
  //添加轮次绑定事件
  if (!addCallBtn) {
      addCallBtn = document.querySelector("#addCallBtn");
  }
  addCallBtn.addEventListener("click", addRoundCallBtn);
  //一键外呼提交按钮绑定事件
  if (!pageSubmitBtn) {
      pageSubmitBtn = document.querySelector("#pageSubmitBtn");
  }
  pageSubmitBtn.addEventListener("click", submitCallDatas);
  //取消按钮绑定事件
  if (!pageCloseBtn) {
      pageCloseBtn = document.querySelector("#pageCloseBtn");
  }
  pageCloseBtn.addEventListener("click", closeCallPageBtn);
  //当前选中数据
  var currentDataCount = document.querySelector("#selectedId");
  currentDataCount.innerText = miIdDatas.length;
  callDatas.data = miIdDatas;
}

//打开一键外呼
function openCallPageBtn() {
  getCaseTable();
  if (miIdDatas.length === 0) {
    showAlert("请勾选数据再外呼");
    return;
  }
  else if(isUproadData){
    showAlert("正在提交数据，请等待完成后再外呼");
    return;
  }
  
  GM_xmlhttpRequest({
      method: "POST",
      url: "http://" + bsc_port + "/call/statusOrCall",
      headers: {
          "Content-Type": "application/json"
      },
      data: callStatsJson,
      onload: function(res) {
          if (res.status == 200) {
              callStatusDatas = JSON.parse(res.responseText + "");
              if (callStatusDatas.statusCode != 200) {
                  showAlert("获取到外呼状态错误");
                  return;
              }
              var planInfo = callStatusDatas.data.planInfo;
              if (!planInfo) {
                clickCall();
              }
              else if(planInfo && planInfo.status > 5){
                clickCall();
              }
              else {
                showAlert("有外呼进度，请打开外呼进度查询");
              }
          }
      },
      onerror: function(err) {
        console.log(err);
        showAlert("请求外呼状态错误");
      }
  });

}
//关闭一键外呼事件
function closeCallPageBtn() {
  //关闭时删除全部插入的轮次
  if (!callList)
      callList = document.querySelector("#callList");
  let addCallItems = callList.querySelectorAll(".addcallItem");
  for (let i = 0; i < addCallItems.length; i++) {
      callList.removeChild(addCallItems[i]);
  }

  page.style.display = "none";
}

//添加轮次按钮事件
function addRoundCallBtn() {

  let addcallItem = document.createElement("div");
  addcallItem.className="addcallItem";
  addcallItem.style.height="50px";
  addcallItem.style.marginBottom="20px";
  addcallItem.innerHTML=`<h5 style="font-size: 12px; font-weight: normal;">第2轮呼叫</h5>
  <div class="callCheck"> 
  <input type="checkbox" checked="true">本人
  <input type="checkbox" checked="true">紧急联系人
  <input type="checkbox" checked="true">所有亲属
  <button style="border: none;color: red; margin-left: 10px;">X</button>
  </div>`;
  callList.appendChild(addcallItem);
  

  let addCallItems = callList.querySelectorAll(".addcallItem");
  for (let i = 0; i < addCallItems.length; i++) {
      let currentAddItem = addCallItems[i];
      currentAddItem.querySelector('h5').innerText = "第" + (i + 2) + "轮呼叫";
      let itemBtn = currentAddItem.querySelector('button');
      itemBtn.addEventListener("click", function() {
          removeRoundCall(itemBtn);
      });
  }
}

//删除当前轮次呼叫
function removeRoundCall(data) {
  var parentNode = data.parentNode.parentNode;
  var grandNode = parentNode.parentNode;
  grandNode.removeChild(parentNode);
  let addCallItems = callList.querySelectorAll(".addcallItem");
  for (let index = 0; index < addCallItems.length; index++) {
      let currentAddItem = addCallItems[index];
      currentAddItem.querySelector('h5').innerText = "第" + (index + 2) + "轮呼叫";
  }
}
//提交外呼表数据
function submitCallDatas() {
  //获取一键外呼表的数据
  var callCount = document.querySelector("#callCount");
  strategy.dialConcurrency = callCount.value;
  //轮次集合
  var callList = document.querySelector("#callList");
  //默认一轮呼叫数据
  var callCheck = callList.querySelector(".callCheck");
  var inputList = callCheck.querySelectorAll('input');

  var callItem = {};
  callItem.callSelf = inputList[0].checked;
  callItem.callDirectRel = inputList[1].checked;
  callItem.callAllRel = inputList[2].checked;
  rounds.push(callItem);
  let addCallItems = callList.querySelectorAll(".addcallItem");
  for (let i = 0; i < addCallItems.length; i++) {
      let currentAddItem = addCallItems[i];
      let addCallItem = {};
      let addInputList = currentAddItem.querySelectorAll('input');
      addCallItem.callSelf = addInputList[0].checked;
      addCallItem.callDirectRel = addInputList[1].checked;
      addCallItem.callAllRel = addInputList[2].checked;
      rounds.push(addCallItem);
  }
  strategy.rounds = rounds;
  callDatas.strategy = strategy;
  var callDatasJson = JSON.stringify(callDatas);
  strategy = {};
  rounds = [];

  GM_xmlhttpRequest({
      method: "POST",
      url: "http://" + bsc_port + "/call/agent",
      headers: {
          "Content-Type": "application/json"
      },
      data: callDatasJson,
      onload: function(res) {
          if (res.status == 200) {
              closeCallPageBtn();
              showAlert("开始一键外呼");
              var callData = JSON.parse(res.responseText + '');
              strategy = {};
              rounds = [];
              if (callData.statusCode != 200) {
                  showAlert("提交数据请求错误");
              }
          }

      },
      onerror: function(err) {
          showAlert("提交数据失败");
      }
  });


}

//插入弹框一键外呼页面
function insertPage() {
  var page = document.createElement("div");
  page.innerHTML = '<div style="position: fixed; z-index: 100; width: 100%; height: 100%; background-color:rgba(0,0,0,0.2); display: none; left: 0;top: 0;" id="page">' +
      '<div style = "width: 500px; height: 500px; position: absolute; left: 50%; top: 50%; margin-top: -250px; margin-left: -250px; background-color: #fff;">' +
      '<div style = "height: 30px; width: 100%; margin-bottom: 20px;  background-color: rgb(39, 39, 214); line-height: 30px; color: white; text-indent:2em">' +
      '一键外呼 <button style = "width: 30px; height:30px;background-color: rgb(39, 39, 214); border: none; color: #fff; float: right;" id = "closePage"> X </button></div>' +
      '<div style="padding-left: 20px; height: 450px; overflow: auto;"> <div style = "background-color: #ddd; margin-bottom: 20px; height: 50px;"> 已选中共 <span style = "color: red;"id = "selectedId">' +
      '</span>条数据 </div> <div style = "height: 30px; margin-bottom: 20px;"> ' +
      '<span style = "background-color: skyblue;"> 设置拨打并发: </span>' +
      '<input id = "callCount" style = "margin-left: 10px; width: 100px;" type = "text" value = "10"> </div>' +
      '<div style = "height: 30px; margin-bottom: 20px;"> <span style = "background-color: skyblue;"> 设置拨打策略: </span> ' +
      '<button id = "addCallBtn" style = "border: none;color: blue;"> 添加轮次  </button> </div>' +
      '<div id = "callList" style = "border: 1px solid #ccc; margin-right: 20px; margin-bottom: 20px;"> <div class = "callItem" style = "height: 50px; margin-bottom: 20px;">' +
      '<h5 style = "font-size: 12px; font-weight: normal;"> 第1轮呼叫 </h5> <div class = "callCheck">' +
      '<input type = "checkbox"  checked = "true" id = "callSelf"> <label for = "callSelf">本人</label>' +
      '<input type="checkbox"  checked="true" id="callDirectRel"> <label for = "callDirectRel"> 紧急联系人 </label>' +
      '<input type = "checkbox"  checked="true"  id = "callAllRel"> <label for ="callAllRel">所有亲属</label> ' +
      '</div> </div> </div>' +
      '<div style="text-align: right; padding-right: 20px;margin-bottom: 20px;"> <button id = "pageSubmitBtn"' +
      'style = "background-color: #234995; color: white; margin-right: 20px; width: 70px; height: 24px; border: none;"> 提交 </button>' +
      '<button id = "pageCloseBtn" style = " width: 70px; height: 24px; border: none;"> 取消 </button> </div> ' +
      ' </div></div></div>';
  document.body.insertBefore(page, document.body.firstChild);
}
//插入外呼进度页面
function insertCallPage() {
  var callPage = document.createElement("div");

  callPage.innerHTML = '<div style="position: fixed; z-index: 100; width: 100%; height: 100%; background-color:rgba(0,0,0,0.2); display: none;  left: 0;top: 0;" id="callpage">' +
      '<div style=" width: 500px; height: 500px; position: absolute; left: 50%; top: 50%; margin-top: -250px; margin-left: -250px; background-color: #fff;">' +
      '<div style=" height: 30px; width: 100%; background-color: rgb(39, 39, 214); line-height: 30px; color: white; text-indent:2em; ">' +
      '坐席外呼状态<button style=" height: 30px; width: 30px; background-color: rgb(39, 39, 214); border: none; color: #fff; float: right; " id="closeCallPage">X</button>' +
      '</div>' +
      ' <div style=" padding: 20px; height: 430px; overflow: auto;">' +
      '<div style="height: 30px; margin: 20px 0; ">' +
      ' <button id="refreshBtn" style="width: 60px; height: 30px; float: right; border: none; background-color: #8ab1d4de; color: white; ">刷新</button>' +
      '</div>' +
      '<div class="callPageBody " style="font-size: 12px; ">' +
      '<div style="height: 35px; width: 100%; border-bottom: 1px dashed #e2e2e2; margin-bottom: 20px; padding-bottom: 8px; ">' +
      '<span style="width: 100px; height: 24px; display: inline-block; padding: 5px; margin-right: 12px; background: #d2e2fcbf; ">开始时间:</span>' +
      '<span>2020-1-1</span>' +
      '</div>' +
      '<div style="height: 35px; width: 100%; border-bottom: 1px dashed #e2e2e2; margin-bottom: 20px; padding-bottom: 8px; ">' +
      '<span style="width: 100px; height: 24px; display: inline-block; padding: 5px; margin-right: 12px; background: #d2e2fcbf; ">状态:</span>' +
      '<span></span>' +
      '<button id="recoverBtn" style="border: none; background: #fff; color: #0758ea; margin-left: 20px; cursor: pointer; ">暂停</button>' +
      '</div>' +
      '<div style="height: 35px; width: 100%; border-bottom: 1px dashed #e2e2e2; margin-bottom: 20px; padding-bottom: 8px; ">' +
      '<span style="width: 100px; height: 24px; display: inline-block; padding: 5px; margin-right: 12px; background: #d2e2fcbf; ">提交案件量:</span>' +
      '<span>1</span></div>' +
      '<div style="height: 35px; width: 100%; border-bottom: 1px dashed #e2e2e2; margin-bottom: 20px; padding-bottom: 8px; "> <' +
      'span style = "width: 100px; height: 24px; display: inline-block; padding: 5px; margin-right: 12px; background: #d2e2fcbf; "> 拨打并发: </span> <' +
      'span> 10 </span> </' +
      'div> <' +
      'div style = "height: 35px; width: 100%; border-bottom: 1px dashed #e2e2e2; margin-bottom: 20px; padding-bottom: 8px; "> <' +
      'span style = "width: 100px; height: 24px; display: inline-block; padding: 5px; margin-right: 12px; background: #d2e2fcbf; "> 执行轮次: </span> <' +
      'span> 1 / 1 </span> </' +
      'div> <' +
      'div style = " width: 100%; border-bottom: 1px dashed #e2e2e2; margin-bottom: 20px; padding-bottom: 8px; "> <' +
      'span style = "width: 100px; height: 24px; display: inline-block; padding: 5px; margin-right: 12px; background: #d2e2fcbf; margin-bottom: 20px;"> 统计: </span> <' +
      'div class = "callContent "' +
      'style = "width: 450px; background: #9c8a8a0a; padding: 20px; display: flex; flex-wrap: wrap; "> <' +
      'p style = "width: 200px; "> 已呼叫 </p> <' +
      'p style = "width: 200px; "> 已呼叫 </p> <' +
      'p style = "width: 200px; "> 已呼叫 </p> <' +
      'p style = "width: 200px; "> 已呼叫 </p> <' +
      'p style = "width: 200px; "> 已呼叫 </p> <' +
      'p style = "width: 200px; "> 已呼叫 </p> <' +
      'p style = "width: 200px; "> 已呼叫 </p> <' +
      'p style = "width: 200px; "> 已呼叫 </p> <' +
      'p style = "width: 200px; "> 已呼叫 </p> </' +
      'div> </' +
      'div> <' +
      'div id="callStatusList" style = " width: 100%; border-bottom: 1px dashed #e2e2e2; margin-bottom: 20px; padding-bottom: 8px; "> <' +
      'span style = "width: 100px; height: 24px; display: inline-block; padding: 5px; margin-right: 12px; background: #d2e2fcbf; margin-bottom: 20px;"> 拨打策略: </span> ' +
      ' </div></div> </div></div> </div> ';
  document.body.insertBefore(callPage, document.body.firstChild);
}

var closeCallPage,refreshBtn;
//外呼进度按钮
function callStatusBtn() {
  let callList,callPage;

  callPage = document.querySelector("#callpage");
  callList = document.querySelector("#callStatusList");
  callPage.style.display = 'block';
  if(!closeCallPage)
    closeCallPage = document.querySelector("#closeCallPage");
  closeCallPage.addEventListener("click", function() {
      callList.innerHTML = `<div id="callStatusList" style=" width: 100%; border-bottom: 1px dashed #e2e2e2; margin-bottom: 20px; padding-bottom: 8px; ">
          <span style="width: 100px; height: 24px; display: inline-block; padding: 5px; margin-right: 12px; background: #d2e2fcbf; margin-bottom: 20px;">拨打策略:</span>
          </div>`;
      callPage.style.display = "none";
  });
  if(!refreshBtn){
    refreshBtn = document.querySelector("#refreshBtn");
    refreshBtn.addEventListener("click", function() {
        callStatusBtn();
    });
  }
  if(!pauseStatusBtn){
    pauseStatusBtn = document.querySelector("#recoverBtn");
    pauseStatusBtn.addEventListener("click",callCtrStatus);
    pauseStatusBtn.disabled=true;
  }
  //获取数据渲染到进度页面
  GM_xmlhttpRequest({
      method: "POST",
      url: "http://" + bsc_port + "/call/statusOrCall",
      headers: {
          "Content-Type": "application/json"
      },
      data: callStatsJson,
      onload: function(res) {
          if (res.status == 200) {
              callList.innerHTML = '<div id="callStatusList" style=" width: 100%; border-bottom: 1px dashed #e2e2e2; margin-bottom: 20px; padding-bottom: 8px; ">' +
                  '<span style="width: 100px; height: 24px; display: inline-block; padding: 5px; margin-right: 12px; background: #d2e2fcbf; margin-bottom: 20px;">拨打策略:</span>' +
                  '</div>';
              callStatusDatas = JSON.parse(res.responseText + "");
              if (callStatusDatas.statusCode != 200) {
                  showAlert("获取到外呼数据错误");
                  return;
              }
              //获取页面内容并赋值
              var c_callPageBody = document.querySelector(".callPageBody");

              var titleContentList = c_callPageBody.querySelectorAll('div');
              var valueEleList = [];
              for (let i = 0; i < 5; i++) {
                  valueEleList[i] = titleContentList[i].querySelectorAll('span')[1];
              }
              var planInfo = callStatusDatas.data.planInfo;
              var callStrategy = callStatusDatas.data.callStrategy;
              var rounds = callStrategy.rounds;
              valueEleList[0].innerText = callStatusDatas.respTime;
              valueEleList[1].innerText = planInfo ? reutrnStatus(planInfo.status) : '未配置';
              valueEleList[2].innerText = planInfo ? planInfo.commitCaseCount : 0;
              valueEleList[3].innerText = callStrategy.dialConcurrency;
              valueEleList[4].innerText = planInfo ? (planInfo.currentRounds + "/" + planInfo.totalRounds) : '0';
              
              //判断状态设置对应的状态按钮
              if(planInfo && planInfo.status){
                let status = Number(planInfo.status);
                if(status === 4 || status === 6){
                  pauseStatusBtn.disabled = false;
                  pauseStatusBtn.innerText = status == 4 ? "暂停" : "恢复";
                  callOutStatus = status;
                }else 
                  pauseStatusBtn.disabled = true;
                  pauseStatusBtn.innerText = "";
              }

              //拨打策略插入
              for (let i = 0; i < rounds.length; i++) {
                  insertCallFun(callList);
              }

              //统计中数据赋值
              var callContent = document.querySelector(".callContent");
              var pList = callContent.querySelectorAll("p");
              var pListContent = [];
              if(planInfo) {
                pListContent.push("已呼叫数量:" + planInfo.alreadyCallCount);
                pListContent.push("坐席接通数量:" + planInfo.agentConnectCount);
                pListContent.push("AI接通数量:" + planInfo.aiConnectCount);
                pListContent.push("接通率:" + planInfo.connectRate);
                pListContent.push("本轮已呼叫数量:" + planInfo.curRoundsAlreadyCallCount);
                pListContent.push("本轮待呼叫数量:" + planInfo.curRoundsWaitCallCount);
                pListContent.push("本轮坐席接通数量:" + planInfo.curRoundsAgentConnectCount);
                pListContent.push("本轮AI接通数量:" + planInfo.curRoundsAiConnectCount);
                pListContent.push("本轮接通率:" + planInfo.curRoundsConnectRate);
              }

              for (let i = 0; i < pListContent.length; i++) {
                  pList[i].innerText = pListContent[i];
              }
              var callFunList = callList.querySelectorAll(".callFun");
              for (let j = 0; j < callFunList.length; j++) {
                  callFunList[j].querySelector("h5").innerText = "第" + (j + 1) + "轮呼叫";
                  let inputList = callFunList[j].querySelectorAll('input');
                  inputList[0].checked = rounds[j].callSelf;
                  inputList[1].checked = rounds[j].callDirectRel;
                  inputList[2].checked = rounds[j].callAllRel;
              }
          }

      },
      onerror: function(err) {
          alert("请求外呼数据错误");
          console.log(err);
      }
  });

}

function reutrnStatus(status) {
  var status1 = Number(status);
  var statusName;
  switch (status1) {
      case 1:
          statusName = "未配置";
          break;
      case 2:
          statusName = "等待下一时刻执行";
          break;
      case 3:
          statusName = "调度中";
          break;
      case 4:
          statusName = "执行中";
          break;
      case 5:
          statusName = "暂停中";
          break;
      case 6:
          statusName = "已暂停";
          break;
      case 7:
          statusName = "停止中";
          break;
      case 8:
          statusName = "已停止";
          break;
      case 9:
          statusName = "已完成";
          break;
      case 10:
          statusName = "已删除";
          break;
      case 11:
          statusName = "失败";
          break;
      default:
          statusName = "失败";
          break;
  }
  return statusName;
}

//拨打策略插入呼叫列表
function insertCallFun(callList) {
  callList.innerHTML += '<div class="callFun" style="width: 400px; background: #9c8a8a0a; padding: 20px; ">' +
      '<h5 style="font-size: 12px; font-weight: normal;">第一轮呼叫</h5>' +
      '<div class = "callCheck">' +
      '<input type="checkbox" value="true" checked="checked" disabled>本人' +
      '<input type="checkbox" value="true" checked="checked" disabled>紧急联系人' +
      '<input type="checkbox" value="true" checked="checked" disabled>所有三方' +
      '</div></div>';
}

var eleAlert;
//增加自定义弹框
function addAlert(){
  GM_addStyle(`.props{
    width: 400px;
    height: 100px;
    position: fixed;
    top: 12vh;
    left: 50%;
    transform: translateX(-200px);
    z-index:150;
  }
  .alertItem{
    position: absolute;
    width: 400px;
    top: 0px;
    left: 0px;
    border: 1px solid #0678F4;
    text-align: center;
    font-size:20px;
    color:#0678F4;
    background-color: #fff;
    box-shadow: 3px 5px 5px #ddd;
    display: block;
  }`);
  let alertEle = document.createElement("div");
  alertEle.className="props";
  eleAlert = document.body.insertBefore(alertEle,document.body.firstChild);
}
//显示消息弹框
function showAlert(text){
  console.log(eleAlert);
  let textEle = document.createElement("p");
  textEle.className="alertItem";
  textEle.innerText=text;
  eleAlert.appendChild(textEle);
  setTimeout(()=>{
    eleAlert.removeChild(textEle);
  },3000);
}
//暂停恢复外呼功能
function callCtrStatus() {
  let callStatusData = {orgId:orgId,customerId:getCookie("userId") + "#"};
  let callStatusJson = JSON.stringify(callStatusData);
  //启用暂停
  if(callOutStatus == 4) {
    pauseOrResertAPI("恢复",callStatusJson,"/call/restore");
  }else if(callOutStatus == 6) {
    pauseOrResertAPI("暂停",callStatusJson,"/call/pause");
  }
}

function pauseOrResertAPI(test,jsonData,urlEnd){
  GM_xmlhttpRequest({
    method: "POST",
    url: "http://" + bsc_port + urlEnd,
    headers: {
        "Content-Type": "application/json"
    },
    data: jsonData,
    onload: function(res) {
        if (res.status == 200) {
          console.log(res.responseText);
          showAlert("状态修改成功");
          pauseStatusBtn.innerText = test;
          callStatusBtn();
        }
    },
    onerror: function(err) {
      console.log(err);
      showAlert("请求外呼状态错误");
    }
});
}
